/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.safetytask.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.koron.common.Excel;
import com.koron.common.StaffAttribute;
import com.koron.common.bean.StaffBean;
import com.koron.common.domain.DataBean;
import com.koron.common.permission.SPIAccountAnno;
import com.koron.safetytask.domain.CustomFormData;
import com.koron.safetytask.service.api.CustomFormDataService;
import com.koron.safetytask.utils.BusinessCode;
import com.koron.system.annotation.Log;
import com.koron.system.discrete.BusinessManipulation;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.web.bind.annotation.*;
import org.swan.bean.MessageBean;
import springfox.documentation.annotations.ApiIgnore;

import java.io.File;
import java.io.InputStream;
import java.util.*;

@Api(tags = "customFormDate", description = "自定义表单数据接口类")
@RestController
@RequestMapping("/customFormDate")
public class CustomFormDateController {

    private final static Logger logger= LoggerFactory.getLogger(CustomFormDateController.class);
    @Autowired
    private CustomFormDataService customFormDataService;

    @ApiOperation("批量新增自定义表单数据接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "tbaleCode", value = "表格code", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "businessId", value = "使用自定义表单业务id", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "customFormDateList", value = "自定义表单数据", required = true, paramType = "query", dataType = "String")
    }
    )
    @RequestMapping(value = "/batchInsert.htm", method = RequestMethod.POST)
    @Log(title = "批量新增自定义表单数据", businessModule = "自定义表单数据", businessManipulation = BusinessManipulation.INSERT)
    public MessageBean<?> batchInsert(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user,
                                      @RequestBody String data) {
        if (null == user) {
            MessageBean<Integer> messageBean = new MessageBean<>();
            messageBean.setCode(BusinessCode.NOT_LOGIN.getCode());
            messageBean.setDescription(BusinessCode.NOT_LOGIN.getDescription());
            return messageBean;
        }
        List<CustomFormData> beanList = new ArrayList<>();
        Date addTime = new Date();
        try {
            if (StringUtils.isNotEmpty(data)) {
                //将字符串转成json
                JSONObject jsonObject = JSONObject.parseObject(data);
                String tbaleCode = jsonObject.getString("tbaleCode");
                String businessId = jsonObject.getString("businessId");
                Integer maxRowId = null; //存储数据表中已有数据的最高rowId
                // 根据表格code，业务id查询表格中数据的最高rowId
                MessageBean<Integer> messageBean = customFormDataService.queryMaxRow(tbaleCode, businessId);
                if (messageBean.getCode() == BusinessCode.SUCCESS.getCode()) {
                    maxRowId = messageBean.getData();
                } else {
                    return messageBean;
                }
                String customFormDateList = jsonObject.getString("customFormDateList");
                if (StringUtils.isNotEmpty(customFormDateList)) {
                    //将字符串转成json
                    JSONArray array = JSON.parseArray(customFormDateList);
                    for (int i = 0; i < array.size(); i++) {
                        JSONArray jsonArray = array.getJSONArray(i);
                        Iterator<Object> it = jsonArray.iterator();
                        int count = 0;
                        while (it.hasNext()) {
                            JSONObject json = (JSONObject) it.next();
                            String keyId = json.getString("keyId");
                            String keyValue = json.getString("key" + count);
                            CustomFormData customFormData = new CustomFormData();
                            // 设置该组数据的行id
                            customFormData.setRowId(i + maxRowId);
                            customFormData.setTbaleCode(tbaleCode);
                            customFormData.setBusinessId(businessId);
                            customFormData.setKeyId(keyId);
                            customFormData.setKeyValue(keyValue);
                            customFormData.setAddUser(user.getCode());
                            customFormData.setAddUserName(user.getName());
                            customFormData.setAddTime(addTime);
                            customFormData.setUpdateTime(addTime);
                            customFormData.setUpdateUser(user.getCode());
                            customFormData.setUpdateUserName(user.getName());
                            MessageBean<Integer> msg = checkCustomFormData(customFormData);
                            if (msg.getCode() == BusinessCode.SUCCESS.getCode()) {
                                beanList.add(customFormData);
                            } else {
                                return msg;
                            }
                            count++;
                        }
                    }
                }
            }
        } catch (Exception e) {
            MessageBean<Integer> messageBean = new MessageBean<>();
            messageBean.setCode(BusinessCode.FAILURE.getCode());
            messageBean.setDescription("json解析失败");
            return messageBean;
        }
        return customFormDataService.batchInsert(beanList);
    }

    @ApiOperation("批量修改自定义表单数据接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "tbaleCode", value = "表格code", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "businessId", value = "使用表格业务id", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "customFormDateList", value = "自定义表单数据", required = true, paramType = "query", dataType = "String")
    }
    )
    @RequestMapping(value = "/batchUpdate.htm", method = RequestMethod.POST)
    @Log(title = "批量修改自定义表单数据", businessModule = "自定义表单数据",  businessManipulation = BusinessManipulation.UPDATE)
    public MessageBean<Integer> batchUpdate(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user,
                                            @RequestBody String data) {
        if (null == user) {
            MessageBean<Integer> messageBean = new MessageBean<>();
            messageBean.setCode(BusinessCode.NOT_LOGIN.getCode());
            messageBean.setDescription(BusinessCode.NOT_LOGIN.getDescription());
            return messageBean;
        }
        List<CustomFormData> beanList = new ArrayList<>();
        Date addTime = new Date();
        try {
            if (StringUtils.isNotEmpty(data)) {
                //将字符串转成json
                JSONObject jsonObject = JSONObject.parseObject(data);
                String tbaleCode = jsonObject.getString("tbaleCode");
                String businessId = jsonObject.getString("businessId");
                String customFormDateList = jsonObject.getString("customFormDateList");
                if (StringUtils.isNotEmpty(customFormDateList)) {
                    //将字符串转成json
                    JSONArray array = JSON.parseArray(customFormDateList);
                    for (int i = 0; i < array.size(); i++) {
                        JSONArray jsonArray = array.getJSONArray(i);
                        Iterator<Object> it = jsonArray.iterator();
                        int count = 0;
                        while (it.hasNext()) {
                            JSONObject json = (JSONObject) it.next();
                            String id = json.getString("id");
                            String rowId = json.getString("rowId");
                            String keyId = json.getString("keyId");
                            String keyValue = json.getString("key" + count);
                            CustomFormData customFormData = new CustomFormData();
                            customFormData.setRowId(Integer.valueOf(rowId));
                            customFormData.setTbaleCode(tbaleCode);
                            customFormData.setBusinessId(businessId);
                            customFormData.setId(id);
                            customFormData.setKeyId(keyId);
                            customFormData.setKeyValue(keyValue);
                            customFormData.setUpdateTime(addTime);
                            customFormData.setUpdateUser(user.getCode());
                            customFormData.setUpdateUserName(user.getName());
                            MessageBean<Integer> messageBean = checkCustomFormData(customFormData);
                            if (messageBean.getCode() == BusinessCode.SUCCESS.getCode()) {
                                beanList.add(customFormData);
                            } else {
                                return messageBean;
                            }
                            count++;
                        }
                    }
                }
            }
        } catch (Exception e) {
            MessageBean<Integer> messageBean = new MessageBean<>();
            messageBean.setCode(BusinessCode.FAILURE.getCode());
            messageBean.setDescription("json解析失败");
            return messageBean;
        }
        return customFormDataService.batchUpdate(beanList);
    }


    @ApiOperation("批量删除自定义表单数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "表单数据id，多个之间用逗号分开", required = true, dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/batchDelete.htm", method = RequestMethod.POST)
    @Log(title = "批量删除自定义表单数据", businessModule = "自定义表单数据", businessManipulation = BusinessManipulation.DELETE)

    public MessageBean<Integer> batchDelete(@SPIAccountAnno @StaffAttribute("_user")
                                            @ApiIgnore StaffBean user, String ids) {
        if (null == user) {
            MessageBean<Integer> messageBean = new MessageBean<>();
            messageBean.setCode(BusinessCode.NOT_LOGIN.getCode());
            messageBean.setDescription(BusinessCode.NOT_LOGIN.getDescription());
            return messageBean;
        }
        List<String> idList = new ArrayList<>();
        if (StringUtils.isNotEmpty(ids)) {
            String[] idArray = ids.split("[,，]");
            idList = Arrays.asList(idArray);
        }
        return customFormDataService.batchDelete(idList);
    }

    @ApiOperation("根据自定义数据表格code，业务id和添加人查询表单详情接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "tbaleCode", value = "表格code", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "businessId", value = "使用表格业务id", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "userCode", value = "人员code", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "userName", value = "人员name", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "当前页", required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", required = false, dataType = "int", paramType = "query")
    })
    @RequestMapping(value = "/details.htm", method = RequestMethod.GET)
    public MessageBean<DataBean<List<Map>>> details(@RequestParam final String tbaleCode, @RequestParam final String businessId,
                                                    @RequestParam(required = false) final String userCode, @RequestParam(required = false) final String userName, @RequestParam(required = false) Integer page, @RequestParam(required = false) Integer pageSize) {
        Integer start = null;
        if (page == null || page <= 0) {
            page = 1;
            if (pageSize == null || pageSize <= 0) {
                pageSize = 15;
            }
        }
        start = (page <= 1) ? 0 : (page - 1) * pageSize;
        MessageBean<DataBean<List<Map>>> messageBean = customFormDataService.queryByCondition(tbaleCode, businessId, userCode, userName, start, pageSize);
        if (null != messageBean.getData()) {
            messageBean.getData().setPageNo(page);
        }
        return messageBean;
    }

    @ApiOperation("导出自定义表单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "tbaleCode", value = "表格code", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "businessId", value = "使用表格业务id", required = true, paramType = "query", dataType = "String")})
    @RequestMapping(value = "/export.htm", method = {RequestMethod.GET})
    public HttpEntity<?> exports(String tbaleCode, String businessId) {
        MessageBean<LinkedHashMap> details = customFormDataService.details(tbaleCode, businessId);
        // 获取自定义表单名
        String name = "";
        File targetFile = new File("static/excel/customForm.xlsx");
        Map<String, Object> map = new LinkedHashMap<>();
        if (null != details.getData()) {
            map = details.getData();
            name = details.getData().get("name").toString();
        }
        try {
            InputStream in = getClass().getClassLoader().getResourceAsStream("static/excel/customForm.xlsx");
            FileUtils.copyInputStreamToFile(in, targetFile);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        String fileName = "自定义表单-" + name;
        return Excel.createFile(fileName, targetFile, "customForm.btl", map);
    }

    private MessageBean<Integer> checkCustomFormData(CustomFormData bean) {
        MessageBean<Integer> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), Integer.class);
        if (StringUtils.isEmpty(bean.getTbaleCode())) {
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription("自定义表单数据表格code不能为空");
            return msg;
        }
        if (StringUtils.isEmpty(bean.getKeyId())) {
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription("自定义表单数据字段id不能为空");
            return msg;
        }
        if (StringUtils.isEmpty(bean.getKeyValue())) {
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription("自定义表单数据表格值不能为空");
        }
        return msg;
    }


    @ApiOperation("根据自定义数据表格code，业务id和添加人查询表单详情接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "tbaleCode", value = "表格code", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "businessId", value = "使用表格业务id", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "当前页", required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", required = false, dataType = "int", paramType = "query")
    })
    @RequestMapping(value = "/detailsAll.htm", method = RequestMethod.GET)
    public MessageBean<DataBean<List<Map>>> detailsAll(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user,
                                                       @RequestParam final String tbaleCode,
                                                       @RequestParam final String businessId,
                                                       @RequestParam(required = false) Integer page,
                                                       @RequestParam(required = false) Integer pageSize,
                                                       @RequestParam(required = false) final String userCode,
                                                       @RequestParam(required = false) final String userName) {
        Integer start = null;
        if (page == null || page <= 0) {
            page = 1;
            if (pageSize == null || pageSize <= 0) {
                pageSize = 15;
            }
        }
        start = (page <= 1) ? 0 : (page - 1) * pageSize;
        MessageBean<DataBean<List<Map>>> messageBean = customFormDataService.queryAllByCondition(user,tbaleCode, businessId, start, pageSize,userCode,userName);
        if (null != messageBean.getData()) {
            messageBean.getData().setPageNo(page);
        }
        return messageBean;
    }
}
